<?php
class Wcpay extends CS_Controller
{
    public function _init()
    {
        $this->load->helper(array('common'));
        $this->load->library('swiftpass/swiftpay', null, 'swiftpay');
	    $this->load->library('alipay/authorization', null, 'authorization');
        $this->load->model('pay_record_model','pay_record');
        $this->load->model('order_base_model','order_base');
        $this->load->model('bind_user_model', 'bind_user');
        $this->load->library('ccbpay/ccbpay', null, 'ccbpay');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('user_transfer_charge_model', 'user_transfer_charge');
        $this->load->model('pay_failure_log_model', 'pay_failure_log');

    }

    /**
     * 威富通支付
     */
    public function swiftpay()
    {
        $payId = $this->input->get('pay_id');
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            $this->alertJumpPre('订单信息有误，或长时间未支付');
        }
        $payRecord = $result->row(0);

        if ((int)$payRecord->bit_state&65536) {
            $this->alertJumpPre('该订单已经支付，无需重新支付');
        }

        $orderBase = $this->order_base->findByPayId($payId);
        if ($orderBase->num_rows() == 0) {
            $this->alertJumpPre('操作失败!');
        }
        $orderBase = $orderBase->row();

        $swiftParam = $this->user_transfer_charge->findBySid($orderBase->sid);
        if ($swiftParam->num_rows() == 0) {
            $this->alertJumpPre('账号未绑定银行参数');
        }
        $swiftParam = $swiftParam->row();

        $notifyUrl = site_url('scenic/paycallback/swiftNotify');
        $callbackUrl = site_url('scenic/payment/swiftReturn');
        $url = $callbackUrl.'?pay_id='. $payRecord->pay_id. '&sign='. $this->createSign($payRecord);
        if (validateWeiXin()) {
            $request = array(
                'service' => 'pay.weixin.jspay',
                'is_raw' => 1, //值为 1：调用原生态微信jsapi；值为 0：不传默认是 0
                'out_trade_no' => $payRecord->pay_id, //商户系统内部的订单号 ,32个字符内、 可包含字母,确保在商户系统唯一
                'body' => mb_substr($payRecord->body, 0, 10), // String(127) 商品描述
                'sub_openid' => $this->getOpenid(), //微信用户关注商家公众号的 openid
                'total_fee' => $payRecord->amount * 100, //总金额，以分为单位，不允许包含任何字、符号
                'notify_url' => $notifyUrl, //接收威富通通知的 URL，需给绝对路径，255字符内格式
                'callback_url' => $callbackUrl, //交易完成后跳转的 URL，需给绝对路径
                'mch_id'  => $swiftParam->mch_id
            );
            $response = $this->swiftpay->submit($request, $swiftParam->key);
            if (! $response) {
                $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $this->swiftpay->getError(), array('status'=>'兴业银行微信支付'));
                redirect('scenic/payment/payError/wx/'. $payRecord->pay_id);
            }
            $jsApiParameters = $this->getJsApiParameters($response['pay_info']);
            $errorUrl = site_url('scenic/payment/payError/wx/'.$payRecord->pay_id);
            $this->load->view('wcpay/wxpay', compact('jsApiParameters', 'url', 'errorUrl'));
        } elseif (validateAliapp()) {
            $request = array(
                'service' => 'pay.alipay.jspay',
                'out_trade_no' => $payRecord->pay_id, //商户系统内部的订单号 ,32个字符内、 可包含字母,确保在商户系统唯一
                'body' => mb_substr($payRecord->body, 0, 10), // String(127) 商品描述
                'total_fee' => $payRecord->amount * 100, //总金额，以分为单位，不允许包含任何字、符号
                'notify_url' => $notifyUrl, //接收威富通通知的 URL，需给绝对路径，255字符内格式
                'callback_url' => $callbackUrl, //交易完成后跳转的 URL，需给绝对路径
                'mch_id'  => $swiftParam->mch_id,
                'buyer_id' => $this->getAlipayUserId()
            );
            $response = $this->swiftpay->submit($request, $swiftParam->key);
            if (! $response) {
                $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $this->swiftpay->getError(), array('status'=>'兴业银行阿里支付'));
                redirect('scenic/payment/payError/ali/'. $payRecord->pay_id);
            }
            $errorUrl = site_url('scenic/payment/payError/ali/'.$payRecord->pay_id);
            $pay_info = $response['pay_info'];
            $this->load->view('wcpay/alipay', compact('pay_info', 'url', 'errorUrl'));
        }
    }

    /**
     * 签名
     */
    private function createSign($payRecord)
    {
        $parameters = array(
            'pay_id'     => $payRecord->pay_id,
            'level'      => $payRecord->level,
            'cat_ids'    => $payRecord->cat_ids,
            'goods_ids'  => $payRecord->goods_ids,
            'goods_nums' => $payRecord->goods_nums,
            'order_ids'  => $payRecord->order_ids,
            'uid'        => $payRecord->uid,
            'amount'     => $payRecord->amount
        );

        $signPars = "";
        ksort($parameters);
        foreach($parameters as $k => $v) {
            if("" != $v && "sign" != $k) {
                $signPars .= $k . "=" . $v . "&";
            }
        }
        $signPars = rtrim($signPars, '&');

        return strtolower(md5($signPars));
    }

    /**
     * 获取微信 openid
     */
    private function getOpenid()
    {
        $openUser = json_decode(get_cookie('bzopen'), TRUE);
        if (empty($openUser['openid'])) {
            $result = $this->bind_user->findByUid($this->uid);
            if ($result->num_rows() == 0 || !$result->row()->open_id) {
                $this->alertJumpPre('该用户未绑定微信号');
            } else {
                return $result->row()->open_id;
            }
        } else {
            return $openUser['openid'];
        }
    }

    /**
     * 微信授权
     */
    private function weChat()
    {
        if (validateWeiXin()) {
            $openUser = json_decode(get_cookie('bzopen'), TRUE);
            if (empty($openUser['openid']) ) {
                include_once(getcwd()."/application/libraries/wxpay/WxPayPubHelper/WxPayPubHelper.php");
                $jsapi = new JsApi_pub();
                if (!isset($_GET['code'])) {
                    $return_url = urlencode(site_url('wcpay/swiftpay'));
                    // $return_url = urlencode(site_url('wcpay/test'));
                    $url = $jsapi->createOauthUrlForCode($return_url);
                    header("Location:$url");
                }
                $jsapi->setCode($_GET['code']);
                return $jsapi->getOpenid();
            } else {
                return $openUser['openid'];
            }
        }
    }

    /**
     * 获取阿里用户编号
     */
    private function getAlipayUserId()
    {
        $openUser = json_decode(get_cookie('bzopen'), TRUE);
        if (empty($openUser['ali_user_id']) ) {
            $result = $this->bind_user->findByUid($this->uid);
            if ($result->num_rows() == 0 && !$result->row()->ali_user_id) {
                $this->alertJumpPre('该用户未绑定支付宝账号');
            } else {
                return $result->row()->ali_user_id;
            }
        } else {
            return $openUser['ali_user_id'];
        }
    }

    /**
     * 支付宝授权
     */
    public function aliAuth()
    {
        $openUser = json_decode(get_cookie('bzopen'), TRUE);
        if (empty($openUser['ali_user_id'])) {
            $authCode = $this->input->get('auth_code');
            if (empty($authCode)) {
                $return_url = site_url('wcpay/swiftpay');
                $appid = $this->authorization->getAppid();
                $url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.$appid .'&scope=auth_userinfo&redirect_uri='. $return_url;
                header("Location:$url");
            }
            $params = $this->authorization->getAutoParams();
            $params['method'] = 'alipay.system.oauth.token';
            $params['code'] = $authCode;
            $params['sign'] = $this->authorization->generateSign($params, 'RSA');
            $alipayTokenResponse = json_decode($this->authorization->curl($params));
            $user_id = $alipayTokenResponse->alipay_system_oauth_token_response->user_id;
            return $user_id;
        } else {
            return $openUser['ali_user_id'];
        }
    }

    /**
     * 过滤微信参数
     */
    private function getJsApiParameters($payInfo)
    {
        $payInfo = json_decode($payInfo);
        return $parameters = json_encode(
            array(
                "appId" => $payInfo->appId, //公众号名称，由商户传入
                "timeStamp"=> $payInfo->timeStamp, //时间戳，自 1970 年以来的秒数
                "nonceStr" => $payInfo->nonceStr, //随机串
                "package" => $payInfo->package,
                "signType" => $payInfo->signType, //微信签名方式
                "paySign" => $payInfo->paySign //微信签名
            )
        );
    }
}